package job

import (
	"fmt"
)

//worker数量
const workerNum int = 5

//定义worker池
type workerPool struct {
	WorkerChan chan *Worker
}

var WorkerPool *workerPool

//初始化worker池
func InitWorkerPool() {

	WorkerPool = &workerPool{
		WorkerChan: make(chan *Worker, workerNum),
	}

	//初始化worker
	for i := 0; i < workerNum; i++ {
		//创建worker
		worker := newWorker(i)
		//启动worker
		worker.Start()

	}
}

//定义worker
type Worker struct {
	//每个worker都需要有一个ID
	ID int
	//接受任务的goroutine
	RepoJobs chan int
	//退出标识
	quit chan bool
}

func (w *Worker) Start() {
	go func() {
		for {
			//将当前worker放到goroutine当中去
			WorkerPool.WorkerChan <- w

			select {
			//获取任务
			case jobID := <-w.RepoJobs:
				//处理任务
				w.handleRepJob(jobID)

			//退出
			case q := <-w.quit:

				fmt.Printf("任务退出 : %v", q)
				return

			}
		}
	}()
}

//业务处理方法
func (w *Worker) handleRepJob(id int) {

	//业务处理
	fmt.Printf("我是 %d 号工人,我的要做的任务编号是 %d\n", w.ID, id)
}

//创建worker
func newWorker(id int) *Worker {

	w := &Worker{
		ID:       id,
		RepoJobs: make(chan int),
		quit:     make(chan bool),
	}

	return w

}

//停止worker
func (w *Worker) Stop() {
	go func() {
		w.quit <- true
	}()

}

//任务调度
func Dispatch() {

	for {

		select {
		case jobID := <-jobQueue:

			go func(jobId int) {
				//从WorkerPool取出一个worker好让他工作
				//注意:Start方法的	WorkerPool.WorkerChan <- w
				worker := <-WorkerPool.WorkerChan
				worker.RepoJobs <- jobId

			}(jobID)
		}
	}

}
